package com.itheima.service.mongo.impl;

import com.itheima.domain.mongo.Friend;
import com.itheima.domain.vo.PageBeanVo;
import com.itheima.service.mongo.FriendService;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

@Service
public class FriendServiceImpl implements FriendService {

    @Autowired
    private MongoTemplate mongoTemplate;

    //保存好友关系
    @Override
    public void saveContact(Long loginUserId, Long replyUserId) {
        //1.保存我与对方的好友关系
        //1.1 查询好友的关系
        Query query = new Query(
                Criteria.where("userId").is(loginUserId)
                .and("friendId").is(replyUserId)
        );
        long count1 = mongoTemplate.count(query, Friend.class);
        if(count1==0){
            //保存关系
            Friend friend1 = new Friend();
            friend1.setCreated(System.currentTimeMillis());
            friend1.setUserId(loginUserId);
            friend1.setFriendId(replyUserId);
            mongoTemplate.save(friend1);
        }

        //2.保存对方与我的好友关系
        //2.1 查询好友的关系
        Query query2 = new Query(
                Criteria.where("userId").is(replyUserId)
                        .and("friendId").is(loginUserId)
        );
        long count2 = mongoTemplate.count(query2, Friend.class);
        if(count2==0){
            //保存关系
            Friend friend2 = new Friend();
            friend2.setCreated(System.currentTimeMillis());
            friend2.setUserId(replyUserId);
            friend2.setFriendId(loginUserId);
            mongoTemplate.save(friend2);
        }
    }

    /**
     * 分页查询好友数据表
     * @param pageNumber
     * @param pageSize
     * @param loginUserId
     * @return
     */
    @Override
    public PageBeanVo findContact(Integer pageNumber, Integer pageSize, Long loginUserId) {
        int startIndex  = (pageNumber -1) * pageSize;
        //查询我的好友列表 传入的我的id即可
        Query query = new Query(
                Criteria.where("userId").is(loginUserId)
        ).skip(startIndex).limit(pageSize);

        List<Friend> friendList = mongoTemplate.find(query, Friend.class);
        long counts = mongoTemplate.count(query, Friend.class);
        return new PageBeanVo(pageNumber , pageSize , counts ,friendList );
    }

    @Override
    public void delete(Long userId, Long friendId) {
        //删除你-她
        mongoTemplate.remove(
                new Query(Criteria.where("userId").is(userId)
                        .and("friendId").is(friendId)), Friend.class);
        //删除她-你
        mongoTemplate.remove(
                new Query(Criteria.where("userId").is(friendId)
                        .and("friendId").is(userId)), Friend.class);
    }
}
